const app = getApp()
const pagePermission = require('../../utils/pagepermission.js')


Page({
  data: {
    orders: [],
    selectedOrderId: '',
    selectedOrder: null,
    orderProducts: [],
    selectedProductsCount: 0,
    loading: false,
    buttonText: '生成生产计划(0个型号)'
  },

  // 计算选中的产品数量
  getSelectedCount() {
    if (!this.data.orderProducts || this.data.orderProducts.length === 0) {
      return 0
    }
    return this.data.orderProducts.filter(item => item.selected === true).length
  },

  // 更新按钮文本
  updateButtonText() {
    const count = this.getSelectedCount()
    const buttonText = this.data.loading ? '生成中...' : `生成生产计划(${count}个型号)`
    console.log('更新按钮文本:', buttonText)
    this.setData({
      buttonText: buttonText
    })
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/generate-production-plan/generate-production-plan')) {
      return
    }
    
    console.log('页面加载，初始数据:', this.data)
    this.loadOrders()
  },

  onShow() {
    console.log('页面显示，当前数据:', this.data)
  },

  // 监控数据变化
  onDataChange() {
    const selectedItems = this.data.orderProducts.filter(item => item.selected)
    console.log('数据变化监控:', {
      orderProducts: this.data.orderProducts,
      selectedProductsCount: this.data.selectedProductsCount,
      selectedItems: selectedItems,
      selectedItemsCount: selectedItems.length
    })
    console.log('每个产品的selected状态:', this.data.orderProducts.map(item => ({
      model_name: item.model_name,
      selected: item.selected
    })))
  },

  // 加载订单列表
  loadOrders() {
    app.request({
      url: '/getOrders',
      method: 'GET',
      data: { limit: 100 }
    }).then(res => {
      if (res.code === 1) {
        const orders = res.data.list || []
        this.setData({
          orders: orders.map(order => ({
            id: order.id,
            name: order.order_name || order.order_no,
            order_no: order.order_no,
            customer_name: order.customer_name,
            delivery_time: order.delivery_time,
            order_models: order.order_models || []
          }))
        })
      }
    }).catch(err => {
      console.error('加载订单失败:', err)
    })
  },

  // 订单选择
  onOrderChange(e) {
    const orderIndex = e.detail.value
    const order = this.data.orders[orderIndex]
    console.log('订单选择:', { orderIndex, order, orders: this.data.orders })
    if (order) {
      this.setData({
        selectedOrderId: order.id,
        selectedOrder: order
      })
      console.log('开始加载订单产品:', order.id)
      this.loadOrderProducts(order.id)
    }
  },

  // 加载订单产品
  loadOrderProducts(orderId) {
    console.log('loadOrderProducts调用:', { orderId, orders: this.data.orders })
    // 从已加载的订单数据中获取产品信息
    const selectedOrder = this.data.orders.find(order => order.id == orderId)
    console.log('找到的订单:', selectedOrder)
    if (selectedOrder && selectedOrder.order_models) {
      const orderProducts = selectedOrder.order_models.map(model => ({
        product_id: model.model.product_id,
        product_name: model.model.product.name,
        model_id: model.model_id,
        model_name: model.model.name,
        quantity: model.quantity,
        color: model.color,
        selected: true // 默认全选
      }))
      console.log('加载产品数据:', orderProducts)
      console.log('检查selected属性:', orderProducts.map(item => ({ 
        model_name: item.model_name, 
        selected: item.selected 
      })))
      this.setData({
        orderProducts: orderProducts
      }, () => {
        const selectedCount = this.getSelectedCount()
        console.log('setData完成，计算选中数量:', selectedCount)
        this.setData({
          selectedProductsCount: selectedCount
        })
        this.updateButtonText()
        this.onDataChange()
      })
    } else {
      // 如果本地没有数据，则从API获取
      app.request({
        url: '/getOrderProducts',
        method: 'GET',
        data: { order_id: orderId }
      }).then(res => {
        console.log('API响应原始数据:', res)
        if (res.code === 1) {
          const orderProducts = (res.data || []).map(item => ({
            ...item,
            selected: true // 默认全选
          }))
          console.log('API加载产品数据:', orderProducts)
          console.log('准备设置数据:', { orderProducts, selectedProductsCount: orderProducts.length })
          this.setData({
            orderProducts: orderProducts
          }, () => {
            const selectedCount = this.getSelectedCount()
            console.log('setData完成，计算选中数量:', selectedCount)
            this.setData({
              selectedProductsCount: selectedCount
            })
            this.updateButtonText()
            console.log('setData完成，当前状态:', this.data)
            this.onDataChange()
          })
        } else {
          console.error('API响应错误:', res)
        }
      }).catch(err => {
        console.error('加载订单产品失败:', err)
      })
    }
  },

  // 产品选择
  onProductSelect(e) {
    console.log('onProductSelect被调用:', e)
    const selectedIds = e.detail.value
    console.log('选中的产品ID:', selectedIds)
    
    // 更新产品选中状态
    const orderProducts = this.data.orderProducts.map(item => {
      item.selected = selectedIds.includes(item.model_id.toString())
      return item
    })
    
    const selectedCount = selectedIds.length
    console.log('更新后数据:', { selectedCount, orderProducts, selectedItems: orderProducts.filter(item => item.selected) })
    
    this.setData({
      orderProducts: orderProducts,
      selectedProductsCount: selectedCount
    })
    this.updateButtonText()
    console.log('setData完成后的状态:', this.data)
    this.onDataChange()
  },

  // 全选
  selectAll() {
    console.log('selectAll被调用')
    const orderProducts = this.data.orderProducts.map(item => ({
      ...item,
      selected: true
    }))
    const selectedCount = orderProducts.length
    console.log('全选后计算数量:', selectedCount)
    this.setData({
      orderProducts: orderProducts,
      selectedProductsCount: selectedCount
    })
    this.updateButtonText()
  },

  // 取消全选
  selectNone() {
    console.log('selectNone被调用')
    const orderProducts = this.data.orderProducts.map(item => ({
      ...item,
      selected: false
    }))
    const selectedCount = 0
    console.log('取消全选后计算数量:', selectedCount)
    this.setData({
      orderProducts: orderProducts,
      selectedProductsCount: selectedCount
    })
    this.updateButtonText()
  },

  // 生成生产计划
  generatePlans() {
    if (!this.data.selectedOrderId) {
      wx.showToast({
        title: '请选择订单',
        icon: 'none'
      })
      return
    }

    if (this.data.selectedProductsCount === 0) {
      wx.showToast({
        title: '请选择要生成生产计划的产品型号',
        icon: 'none'
      })
      return
    }

    const selectedProducts = this.data.orderProducts.filter(item => item.selected)
    const productNames = selectedProducts.map(item => `${item.product_name}-${item.model_name}`).join('、')
    
    wx.showModal({
      title: '确认生成',
      content: `确定要为订单【${this.data.selectedOrder.name}】生成生产计划吗？\n\n将生成${this.data.selectedProductsCount}个产品型号的生产计划：\n${productNames}`,
      success: (res) => {
        if (res.confirm) {
          this.doGeneratePlans()
        }
      }
    })
  },

  // 执行生成
  doGeneratePlans() {
    this.setData({ loading: true })

    const selectedProducts = this.data.orderProducts.filter(item => item.selected)
    const modelIds = selectedProducts.map(item => item.model_id)

    console.log('准备发送的数据:', {
      order_id: this.data.selectedOrderId,
      model_ids: modelIds,
      selectedProducts: selectedProducts
    })

    app.request({
      url: '/generateProductionPlanFromOrder',
      method: 'POST',
      data: { 
        order_id: this.data.selectedOrderId,
        model_ids: JSON.stringify(modelIds)
      }
    }).then(res => {
      this.setData({ loading: false })
      if (res.code === 1) {
        wx.showToast({
          title: res.msg || '生成成功',
          icon: 'success'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg || '生成失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      this.setData({ loading: false })
      console.error('生成生产计划失败:', err)
      wx.showToast({
        title: '生成失败',
        icon: 'none'
      })
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '-'
    const date = new Date(timestamp * 1000)
    return date.toLocaleDateString()
  }
})
